package com.yangziqiang.utils;

import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Map;

/**
 * @ClassName HighLightResultMapper
 * @Description TODO
 * @Author 18516
 * @DATE 2021/12/30 09:31:30
 * @Version 1.0
 */
public class HighLightResultMapper implements SearchResultMapper {
    @Override
    public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
        ArrayList<T> list = new ArrayList<>();
        SearchHits searchHits = response.getHits();
        SearchHit[] hits = searchHits.getHits();
        long totalHits = searchHits.getTotalHits();
        if (hits.length > 0) {
            for (SearchHit hit : hits) {
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                String sourceAsString = hit.getSourceAsString();
                T t = JSON.parseObject(sourceAsString, clazz);
                Field[] fields = clazz.getDeclaredFields();
                for (Field field : fields) {
                    field.setAccessible(true);
                    String name = field.getName();
                    if (highlightFields.containsKey(name)) {
                        HighlightField highlightField = highlightFields.get(name);
                        String s = highlightField.getFragments()[0].toString();
                        try {
                            field.set(t, s);
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }
                }
                list.add(t);
            }
        }
        AggregatedPageImpl<T> ts = new AggregatedPageImpl<>(list, pageable, totalHits);
        return ts;
    }

    @Override
    public <T> T mapSearchHit(SearchHit searchHit, Class<T> aClass) {
        /*  <template slot-scope="scope">
          <p v-html="scope.row.cname"></p>
        </template>   */
        return null;
    }

}
